<template>
  <div>
    <el-form ref="form" label-position="top" :disabled="readonly">
      <k-section type="simple">
        <template #head>
          <el-form-item :label="$t('business.workload.schedule_type')">
            <k-segment
              v-model="uiState.schedulingType"
              class="w-full"
              :options="options.scheduling_type_list"
              @change="onScheduleTypeChange"
            />
            <!-- <ko-data-item
              v-model="uiState.schedulingType"
              itemType="radio"
              :radios="options.scheduling_type_list"
            /> -->
          </el-form-item>
        </template>
        <el-collapse-transition>
          <el-row v-if="uiState.schedulingType === 'specificNode'">
            <el-col :span="24">
              <el-form-item :label="$t('business.workload.node_name')" required>
                <ko-data-item
                  v-model:model-value="spec.nodeName"
                  class="w-full"
                  item-type="select"
                  :selections="nodeList"
                  :val-prop="{
                    label: 'metadata.name',
                    value: 'metadata.name',
                    key: 'metadata.name'
                  }"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <div v-else-if="uiState.schedulingType === 'nodeSelector'">
            <KoKvobjectTable v-model="spec.nodeSelector" editable />
            <div class="float-right">
              <el-button
                icon="Plus"
                circle
                @click="spec.nodeSelector[''] = ''"
              />
            </div>
          </div>
        </el-collapse-transition>
      </k-section>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { NodeInfo, PodSpec } from "@/views/domain/kubeHud/api/k8s";
import { objectToList } from "@/views/domain/kubeHud/utils";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import KSegment from "@/views/domain/kubeHud/views/components/k-segment/index.vue";
import KSection from "@/views/domain/kubeHud/views/components/k-section/index.vue";
import { onMounted, reactive } from "vue";
import { useI18n } from "vue-i18n";
import KoKvobjectTable from "../ko-kvobject-table.vue";

const { t } = useI18n();

const spec = defineModel<PodSpec>("spec");

type Prop = {
  readonly?: boolean;
  nodeScheduleType?: string;
  nodeList?: NodeInfo[];
};

const props = defineProps<Prop>();

const uiState = reactive({
  schedulingType: props.nodeScheduleType || "anyNode",
  nodeName: "",
  labels: [], // ["k : v"]
  nodeSelector: "", // "k : v"
  matchNode: "" // "node1,node2"
});

const options = reactive({
  nodeList: props.nodeList ?? [],
  scheduling_type_list: [
    {
      label: t("business.workload.any_node"),
      value: "anyNode"
    },
    {
      label: t("business.workload.specific_node"),
      value: "specificNode"
    },
    {
      label: t("business.workload.match_rules"),
      value: "nodeSelector"
    }
  ]
});

const onScheduleTypeChange = (t: string) => {
  if (t === "nodeSelector") {
    spec.value.nodeSelector = { "": "" };
  }
};

const makeLabelStr = (key: string, val: any): string => {
  return `${key} : ${val}`;
};
const parseLabelStr = (label: string): { key: string; value: string } => {
  const [key, value] = label.split(" : ");
  return { key, value };
};

// const parseNodesInfo = (nodeList: NodeInfo[]) => {
//   uiState.nodeNameList = nodeList.map(element => {
//     return element.metadata?.name ?? "";
//   });

//   uiState.labels = nodeList.flatMap(
//     node =>
//       objectToList(node.metadata?.labels)?.map(label =>
//         makeLabelStr(label.key, label.value)
//       ) ?? []
//   );
// };

const getMatchNode = (nodeList: NodeInfo[]) => {
  if (!uiState.nodeSelector || uiState.nodeSelector === "") {
    // uiState.matchNode = uiState.nodeNameList.join(",");
  }

  //
  const { key: labelKey, value: labelValue } = parseLabelStr(
    uiState.nodeSelector
  );

  const matchNodeNames: string[] = [];
  for (const node of nodeList) {
    if (node.metadata?.labels?.[labelKey] === labelValue) {
      matchNodeNames.push(node.metadata?.name ?? "");
    }
  }

  uiState.matchNode = matchNodeNames.join(",");
};

const reloadspec = () => {
  if (!spec.value) return;
  if (spec.value.nodeSelector) {
    uiState.schedulingType = "nodeSelector";

    const lastLabel = objectToList(spec.value.nodeSelector)?.findLast(v => !!v);
    if (lastLabel) {
      uiState.nodeSelector = makeLabelStr(lastLabel.key, lastLabel.value);
    }
  } else if (spec.value.nodeName) {
    uiState.schedulingType = "specificNode";
    uiState.nodeName = spec.value.nodeName;
  } else {
    uiState.schedulingType = "anyNode";
  }
};

onMounted(() => {
  reloadspec();
});
</script>
